package com.tools.commons.config;

import com.google.common.collect.Lists;
import com.tools.commons.config.properties.SwaggerProperties;
import com.tools.commons.response.ResponseCode;
import com.tools.commons.utils.EncryptDecryptUtil;
import com.tools.commons.utils.IdGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.AllowableListValues;
import springfox.documentation.service.AllowableValues;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author wangminggen
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    SwaggerProperties swaggerProperties;

    public Swagger2Config(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    private final List<ResponseMessage> globalResponses = Arrays.asList(
            new ResponseMessageBuilder().code(200).message("Success").build(),
            new ResponseMessageBuilder().code(400).message("Bad request").build(),
            new ResponseMessageBuilder().code(401).message("Unauthorized").build(),
            new ResponseMessageBuilder().code(403).message("Forbidden").build(),
            new ResponseMessageBuilder().code(404).message("Not found").build(),
            new ResponseMessageBuilder().code(500).message("Internal server error").build());

    @Bean
    public Docket createRestApi() {
        return buildApiDocket()
                .globalOperationParameters(globalParams())
                .enable(swaggerProperties.isEnable());
    }

    private Docket buildApiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                // .groupName(swaggerProperties.getGroupName())
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.ant(swaggerProperties.getAntPattern()))
                .build()
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.GET, globalResponses)
                .globalResponseMessage(RequestMethod.POST, globalResponses)
                .globalResponseMessage(RequestMethod.DELETE, globalResponses)
                .globalResponseMessage(RequestMethod.PUT, globalResponses)
                .directModelSubstitute(Temporal.class, String.class)
                .globalOperationParameters(globalParams());
    }

    private List<Parameter> globalParams() {
        AllowableValues val = new AllowableListValues(Lists.newArrayList("en_US", "zh_CN"), "string");
        Parameter lang = new ParameterBuilder()
                .name("lang")
                .description("国际化参数")
                .modelRef(new ModelRef("string"))
                .parameterType("header") //header
                .required(false)
                .defaultValue("zh_CN")
                .allowableValues(val)
                .build();

        Parameter token = new ParameterBuilder()
                .name("token")
                .description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header") //header
                .required(false)
                .defaultValue(IdGenerator.uuid())
                .build();

        Parameter ts = new ParameterBuilder()
                .name("ts")
                .description("ts")
                .modelRef(new ModelRef("string"))
                .parameterType("query") //header
                .required(false)
                .defaultValue("ts")
                .build();

        Parameter nonce = new ParameterBuilder()
                .name("nonce")
                .description("nonce")
                .modelRef(new ModelRef("string"))
                .parameterType("query") //header
                .required(false)
                .defaultValue("notice")
                .build();

        Parameter sign = new ParameterBuilder()
                .name("sign")
                .description("sign")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .defaultValue(EncryptDecryptUtil.md5Hex("dev"))
                .build();

        return Arrays.asList(lang, token, ts, nonce, sign);
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("api层相关接口")
                // .termsOfServiceUrl("")
                // .version("1.0")
                // .contact(new Contact("tools", "https://github.com", "@"))
                // .license("GNU General Public License v3.0")
                // .licenseUrl("https://github.com")
                .build();
    }

    private List<ResponseMessage> customerResponseMessage() {
        List<ResponseMessage> list = new ArrayList<>();
        ResponseCode[] values = ResponseCode.values();
        for (ResponseCode value : values) {
            list.add(new ResponseMessageBuilder().code(value.getCode()).message(value.getDefaultMsgTemplate()).build());
        }
        return list;
    }
}
